<template>
  <div class="checkPackage">
    <div class="title">
      <navTitle :navArr="navArr">
      </navTitle>
    </div>
    <div class="quickBuy">
      <headsTitle title="快捷采购">
        <div class="insert" slot="content">
          <div class="head">
            <span class="tables">表格内商品</span>
            <span class="num">数量</span>
            <span class="expect">请选择您期望的礼品包</span>
          </div>
          <ul class="list">
            <li v-for="(item, index) in tableData" :key="index">
              <p>{{ item.productName }}</p>
              <span>{{ item.totalNum }}</span>
              <div class="package">
                <myPackage :isFar="isFar(item)" @setIdChange="setIdChange($event, index)" :titlePackage="item.productName"></myPackage>
              </div>
            </li>
          </ul>
          <div class="comment">
            <p class="left">
              备注：我们统一使用
              <strong>圆通</strong>
              快递发货
            </p>
            <p class="price">
              总价：
              <em>{{ payTotal }}元</em>
            </p>
          </div>
          <div class="footer">
            <b class="button-w" @click="goBack">上一步</b>
            <b class="button-n" @click="surePayTest">确认支付</b>
          </div>
        </div>
      </headsTitle>
    </div>
    <div class="alertGroup">
      <payFail v-if="errorType==1"></payFail>
      <tips v-if="errorType==2"></tips>
      <noMoney v-if="errorType==3" @closeNoMoney="closeNoMoney" :money="leftMoney"></noMoney>
    </div>
  </div>
</template>
<script type="text/ecmascript-6">
import NavTitle from '../../base/navTitle/index'
import HeadsTitle from '../../base/headsTitle/index'
import MyPackage from '../../base/myPackage/index'
import PayFail from '../../base/alert/payFail'
import Tips from '../../base/alert/tips'
import NoMoney from '../../base/alert/noMoney'
import { mapGetters, mapActions } from 'vuex'
export default {
  name: 'checkPackage',
  components: {
    NavTitle,
    HeadsTitle,
    MyPackage,
    PayFail,
    Tips,
    NoMoney
  },
  data () {
    return {
      navArr: ['立即采购'],
      errorType: -1,
      leftMoney: 0,
      tableData: [], // 表格内数组
      payTotal: 0
    }
  },
  computed: {
    postProductList: {
      get: function () {
        let arr = this.tableData
        let postArr = []
        for (let i = 0; i < arr.length; i++) {
          postArr.push({
            productName: arr[i].productName,
            setId: '',
            money: 0,
            totalNum: arr[i].totalNum,
            normalNum: arr[i].normalNum,
            farNum: arr[i].farNum
          })
        }
        return postArr
      },
      set: function (val) {
        return val
      }
    },
    ...mapGetters([
      'userInfo',
      'sellerInfo',
      'autoTable',
      'tables'
    ])
  },
  methods: {
    goBack () {
      window.history.go(-1)
    },
    isFar (item) { // 处理偏远/非偏远的数量
      return {
        farNum: item.farNum,
        normalNum: item.normalNum
      }
    },
    setIdChange (arr, index) { // 礼品包选定 arr [ setId, money ]
      if (arr[0] !== '') {
        this.postProductList[index].setId = arr[0]
        this.postProductList[index].money = arr[1]
        this.priceTotal()
      } else {
        this.postProductList[index].setId = ''
        this.postProductList[index].money = 0
        this.priceTotal()
      }
    },
    priceTotal () { // 计算总价个
      let arr = this.postProductList
      let total = 0
      for (let i = 0; i < arr.length; i++) {
        total = total + arr[i].money
      }
      this.payTotal = total.toFixed(2)
    },
    surePayTest () { // 支付之前的为空校验
      let arr = this.postProductList
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].setId === '') {
          this.$message({
            message: `第${i + 1}条请选择礼品包`,
            type: 'warning'
          })
          return false
        }
      }
      this.sureCreatOrder()
    },
    sureCreatOrder () { // 校验都已选择礼品包 发送生成订单请求
      let url = ''
      if (this.$route.query.tableType === 'autoTable') { // 智能发包请求地址
        url = '/file/task/parseFile/smart'
      } else if (this.$route.query.tableType === 'tables') { // 表格普通上传
        url = '/file/task/parseFile/'
      }
      this.$ajax.post(url, {
        uploadFileName: this[this.$route.query.tableType].uploadFileName,
        shopType: this[this.$route.query.tableType].shopType,
        logisticsType: '1',
        sellerAccountId: this.userInfo.sellerAccountId,
        productNames: this.postProductList,
        filePostfix: this[this.$route.query.tableType].filePostfix,
        importType: this.$route.query.tableType === 'tables' ? '2' : this.$route.query.tableType === 'autoTable' ? '3' : '1' // 1 手工 2 普通 3 智能
      }).then((data) => {
        if (data.data.code === '200') {
          let res = data.data.data
          if (res.code === -1) {
            this.$alert('"' + res.productName + '"' + res.msg + '请重新选择商品', '提示', {
              confirmButtonText: '确定',
              callback: action => {
              }
            })
          } else {
            this.surePayPost(res.orderId)
          }
        } else {
          this.$message({
            message: data.data.message,
            type: 'warning'
          })
        }
      }).catch((err) => {
        console.error(err)
        this.$message({
          message: '生意太火爆了, 请稍后再试',
          type: 'error'
        })
      })
    },
    surePayPost (orderId) { // 确认请求支付接口
      if (this.sellerInfo.balance - this.payTotal < 0) {
        this.leftMoney = (this.payTotal - this.sellerInfo.balance).toFixed(2)
        this.errorType = 3
      } else {
        this.$confirm('确认支付该订单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$ajax.post('/api/order/operate/pay', {
            orderId: orderId
          }).then((data) => {
            if (data.data.code === '200') {
              if (data.data.data.code === 0) {
                this.$message({
                  message: '支付成功',
                  type: 'success'
                })
                this.$router.push({ name: 'paySuccess', query: { orderId: orderId } })
              } else if (data.data.data.code === -1) {
                this.$message({
                  message: '"' + data.data.data.productName + '"' + data.data.data.msg,
                  type: 'warning'
                })
                this.$alert('"' + data.data.data.productName + '"' + data.data.data.msg + '请撤销订单后选择其他商品重新下单', '提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$router.push({ name: 'orderManger' })
                  }
                })
              } else {
                this.$message({
                  message: data.data.data.msg,
                  type: 'warning'
                })
              }
            } else {
              this.$message({
                message: data.data.message,
                type: 'warning'
              })
            }
          }).catch((err) => {
            console.error(err)
            this.$message({
              message: '生意太火爆了, 请稍后再试',
              type: 'error'
            })
          })
        })
      }
    },
    closeNoMoney () { // 关闭余额不足弹框
      this.errorType = -1
      this.$router.push({ name: 'orderManger' })
    },
    ...mapActions([
      'setCommonPackage'
    ])
  },
  mounted () {
    if (this.$route.query.tableType === 'autoTable') {
      this.tableData = this.autoTable.productNames
    } else if (this.$route.query.tableType === 'tables') {
      this.tableData = this.tables.productNames
    }
  }
}
</script>
<style lang="stylus" rel="stylesheet/stylus" scoped>
@import '../../../assets/stylus/index.styl'
.checkPackage
  .quickBuy
    margin-top 20px
    .insert
      padding 20px 50px
      .head
        display flex
        border 1px solid #dddddd
        background #F6F6F6
        border-bottom none
        padding 0 25px
        fontSize($fontSize, 48px, $fontColor)
        span
          text-align center
        .tables
          width 200px
        .num
          width 100px
        .expect
          flex 1
      .list
        border 1px solid #dddddd
        li
          display flex
          align-items center
          padding 20px 25px
          border-bottom 1px solid #dddddd
          &:last-child
            border none
          p
            width 200px
          span
            width 100px
            text-align center
          .package
            flex 1
      .comment
        display flex
        justify-content space-between
        p
          fontSize($fontSize, 48px, $fontColor)
          strong
            color $fontColor-o
          em
            color $mainColor
        .left
          color $fontColor-gray
        .price
          font-size $fontSize-m
      .footer
        margin-top 20px
        text-align center
</style>
